/**
 * 
 *  @project Air Traff Monitor
 * 
 *  @author M.Emre ATASEVER <m.emre.atas@gmail.com>
 *  @author M.Burak ALKAN <mburakalkan@gmail.com>
 *  @author H.Burak KARAMIK <bkaramik@gmail.com>
 *
 *	`Air Traffic Monitor' is distributed in the hope that it will be useful,
 *	but WITHOUT ANY WARRANTY; without even the implied warranty of
 *	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *	GNU General Public License for more details.
 *
 *	You should have received a copy of the GNU General Public License
 *	along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 */
 
#include "netview.h"

#include <QHeaderView>
#include <QSettings>
#include <QFileDialog>
#include <QFile>
#include <QApplication>
#include <QClipboard>
#include <QSortFilterProxyModel>


QList<QVariant> orlist()
{
QList<QVariant> l;
for(int i = 0;i < 52;i++)
	l << i;
return l;
}

QMenu* QKismetTreeView::appendMenu(QString title,const QStringList *titles,const QStringList *commands,QMenu *menu, int off, int cnt)
{
	int j = cnt;
	int i = off;
	QMenu *m = new QMenu(title);
	menus.append(m);
	for (;i < j;i++)
	{
		QKismetAction *a = new QKismetAction(commands->at(i),titles->at(i),i,this);	
		actions.append(a);
		m->addAction(a);
		connect(a,SIGNAL(triggered()),this,SLOT(toggleColumn()));
	}
	if(menu)
		menu->addMenu(m);
	return m;
}

QKismetTreeView::QKismetTreeView(QAbstractItemModel *mod)
{
	kmod	= (KismetItemModel*)mod;
	header()->setClickable(true);
	setSortingEnabled(true);
	
	proxy.setSourceModel(mod);
	proxy.setDynamicSortFilter(true);
	proxy.setFilterKeyColumn(1);
	proxy.setSortRole(Qt::UserRole);
	setModel(&proxy);
	
	
	popupMenu	= new QMenu();
	
	asave	= popupMenu->addAction(QIcon(":/img/document-save.png"),"Save...");
	connect(asave,SIGNAL(triggered()),this,SLOT(saveContents()));
	
	acopy	= popupMenu->addAction(QIcon(":/img/edit-copy.png"),"Copy");
	connect(acopy,SIGNAL(triggered()),this,SLOT(copyContents()));

	asel	= popupMenu->addAction(QIcon(":/img/edit-select-all.png"),"Select all");
	connect(asel,SIGNAL(triggered()),this,SLOT(selectAll()));

	aclear	= popupMenu->addAction(QIcon(":/img/edit-clear.png"),"Clear");
	connect(aclear,SIGNAL(triggered()),this,SLOT(cleared()));
	
	setContextMenuPolicy(Qt::CustomContextMenu);
	connect(this,SIGNAL(customContextMenuRequested(const QPoint&)),this,SLOT(showPopupMenu(const QPoint&)));
	asave->setDisabled(true);
	acopy->setDisabled(true);
	asel->setDisabled(true);
	aclear->setDisabled(true);


	setSelectionMode(QAbstractItemView::ExtendedSelection);
}

QKismetTreeView::~QKismetTreeView()
{
	qDeleteAll(menus);
	qDeleteAll(actions);
	delete popupMenu;	
	delete kmod;
}

void QKismetTreeView::rowsInserted(const QModelIndex& parent,int start, int end)
{
	QTreeView::rowsInserted(parent,start,end);
	asave->setDisabled(false);
	acopy->setDisabled(false);
	asel->setDisabled(false);
	aclear->setDisabled(false);
}

void QKismetTreeView::saveContents()
{
	QString fileName = QFileDialog::getSaveFileName(this,
			     tr("Save File"), "", "Text Files (*.log *.txt);;All Files (*.*)");
	if(fileName == "")
		return;
	QFile file(fileName);
	if(!file.open(QIODevice::WriteOnly | QIODevice::Truncate | QIODevice::Text))
		return;
	QTextStream out(&file);
	
	QList<int> cols;
	int j	= header()->count();
	for(int i = 0; i < j;i++)
		if(!header()->isSectionHidden(i))
			cols << i;
	
	getIndexData(QModelIndex(),false,&cols,out);
	file.close();
}

void QKismetTreeView::copyContents()
{
	QList<int> cols;
	int j 	= header()->count();
	for(int i = 0; i < j;i++)
		if(!header()->isSectionHidden(i))
			cols << i;
	QString out;
	getIndexData(QModelIndex(),true,&cols,out);
	QApplication::clipboard()->setText(out);
}

void QKismetTreeView::getIndexData(QModelIndex ix, bool selonly, QList<int> *cols, QTextStream& out)
{
	QAbstractItemModel *mod		= model();
	QItemSelectionModel *sel	= selectionModel();
	QModelIndex item;

	int k 	= cols->count();
	int j	= mod->rowCount(ix);
	for(int i = 0;i < j;i++)
	{
		item	= mod->index(i,0,ix);
		if(!selonly || sel->isSelected(item)) 
		{
			for(int j = 0; j < k;j++)
			{
				out	<< mod->data(mod->index(i,cols->at(j),ix)).toString();
				if(j != k-1)
					out	<< '\t';
			}
			out	<< '\n';
		}
		getIndexData(item,selonly,cols,out);
	}
}

void QKismetTreeView::getIndexData(QModelIndex ix, bool selonly, QList<int> *cols, QString& out)
{
	QAbstractItemModel *mod		= model();
	QItemSelectionModel *sel	= selectionModel();
	QModelIndex item;

	int k 	= cols->count();
	int j	= mod->rowCount(ix);
	for(int i = 0;i < j;i++)
	{
		item	= mod->index(i,0,ix);
		if(!selonly || sel->isSelected(item)) 
		{
			for(int j = 0; j < k;j++)
			{
				out	+= mod->data(mod->index(i,cols->at(j),ix)).toString();
				if(j != k-1)
					out	+= '\t';
			}
			out	+= '\n';
		}
		getIndexData(item,selonly,cols,out);
	}
}

QList<QAction*> QKismetTreeView::menuActions()
{
	return popupMenu->actions();
}

void QKismetTreeView::showPopupMenu(const QPoint& pos)
{
	popupMenu->exec(viewport()->mapToGlobal(pos));
}


void QKismetTreeView::selectionChanged(const QItemSelection& selected, const QItemSelection& deselected)
{
	QTreeView::selectionChanged(selected,deselected);
	acopy->setEnabled(selected.size() > 0);
}

void QKismetTreeView::cleared()
{
	kmod->clear();
	asave->setDisabled(true);
	acopy->setDisabled(true);
	asel->setDisabled(true);
	aclear->setDisabled(true);
}

void QKismetTreeView::showHeadMenu(const QPoint& pos)
{

	headMenu->exec(header()->mapToGlobal(pos));
}


void QKismetTreeView::toggleColumn()
{
	QKismetAction *a = (QKismetAction*)sender();
	if(a->isChecked())
		header()->showSection(a->i);
	else
		header()->hideSection(a->i);
	emit setOption(a->propName,a->isChecked());

}

void QKismetTreeView::WriteSettings(QString &secname)
{
	QHeaderView *head = header();
	QList<QVariant> cols,order,size;
	int j = head->count();
	for(int i = 0;i< j;i++)
	{
		if(!head->isSectionHidden(i))
			cols << i;
		size	<< head->sectionSize(i);
		order	<< head->visualIndex(i);
	}
	QSettings settings("qkismet", "qkismet");
	settings.beginGroup(secname);
	settings.setValue("columns", cols);
	settings.setValue("order", order);
	settings.setValue("size", size);
	settings.endGroup();
}

void QKismetTreeView::RestoreSettings(QString &secname, QList<QAction*> &acts,QList<QVariant> initCols)
{
	QHeaderView *head = header();

	QSettings settings("qkismet", "qkismet");
	settings.beginGroup(secname);
	QList<QVariant> cols	= settings.value("columns",  QVariant(initCols)).toList();
	QList<QVariant> order	= settings.value("order", QVariant(orlist())).toList();
	QList<QVariant> size	= settings.value("size", QVariant(QList<QVariant>())).toList();
	settings.endGroup();

	int j = head->count();
	for(int i = 0;i < j;i++)
	{
		head->moveSection(head->visualIndex(i),order[i].toInt());
		if(size.size() > 0 && size[i].toInt() > 0)
			head->resizeSection(i,size[i].toInt());
		if(cols.indexOf(i) == -1)
			head->hideSection(i);
		else
			acts[i]->setChecked(true);
	}
}

QList<QVariant> QKismetTreeView::InitialColumns()
{
	return (QList<QVariant>() <<0<<1<<2);
}

QKismetAction::QKismetAction(const QString& pname, const QString& text,int ix,QObject *parent) : QAction(text,parent)
{
	propName = pname;
	setCheckable(true);
	i = ix;
}


